from django.contrib.auth.models import AbstractUser
from django.db import models

from users import constants
from utils import tjws
from utils.models import BaseModel


class User(AbstractUser):
    """用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    email_active = models.BooleanField(default=False)
    default_address = models.OneToOneField('users.Address', related_name='user_addr', null=True, blank=True)

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    # 通过当前登录用户的id加密成token发送给前端加上url，完成验证url的发送
    # 用user_id加密成token是方便我们查询然后给该用户激活邮箱
    def generate_verify_email_token(self):
        # 用Id来做加密
        data = {"user_id": self.id}
        # 加密
        token = tjws.dumps(data, constants.USER_EMAIL_TOKEN_EXPIRES)
        # 返回url
        return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token


class Address(BaseModel):
    # 所属用户
    user = models.ForeignKey(User, related_name='addresses')
    # 名称，如‘家’、‘公司’
    title = models.CharField(max_length=20)
    # 收件人
    receiver = models.CharField(max_length=20)
    # 省
    province = models.ForeignKey('areas.Area', related_name='province_addr')
    # 市
    city = models.ForeignKey('areas.Area', related_name='city_addr')
    # 区
    district = models.ForeignKey('areas.Area', related_name='district_addr')
    # 详细地址
    place = models.CharField(max_length=200)
    # 手机
    mobile = models.CharField(max_length=11)
    # 固定电话
    tel = models.CharField(max_length=20, null=True, blank=True)
    # 邮箱
    email = models.CharField(max_length=20, null=True, blank=True)
    # 逻辑删除
    is_delete = models.BooleanField(default=False)